package com.yanchangapp.ui.activity.purchase;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.PsDetailCommentAdapter;
import com.yanchangapp.adapter.PsDetailProductAdapter;
import com.yanchangapp.commom.OrderStatus;
import com.yanchangapp.model.bean.OrderCommentBean;
import com.yanchangapp.model.bean.OrderDetailBean;
import com.yanchangapp.model.bean.OrderProductBean;
import com.yanchangapp.ui.presenter.OrderDetailAtPresenter;
import com.yanchangapp.ui.view.OrderDetailAtView;
import com.yanchangapp.widget.SpannableMoney;
import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.DisplayHelper;
import com.zxl.baselib.widget.NiceNestedScrollView;
import com.zxl.baselib.widget.TipDialog;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 订单详情页面....
 */
public class POrderDetailActivity extends BaseActivity<OrderDetailAtView, OrderDetailAtPresenter> implements OrderDetailAtView {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ibToolbarMore)
    ImageButton ibToolbarMore;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.tvTag)
    TextView tvTag;
    @BindView(R.id.tvTextSingleName)
    TextView tvTextSingleName;
    @BindView(R.id.userHead)
    RelativeLayout userHead;
    @BindView(R.id.tvUserDept)
    TextView tvUserDept;
    @BindView(R.id.tvOrderNoTitle)
    TextView tvOrderNoTitle;
    @BindView(R.id.tvOrderCompanyTitle)
    TextView tvOrderCompanyTitle;
    @BindView(R.id.tvOrderAreaTitle)
    TextView tvOrderAreaTitle;
    @BindView(R.id.rvOrderDetail)
    RecyclerView rvOrderDetail;
    @BindView(R.id.llApproveTitle)
    LinearLayout llApproveTitle;
    @BindView(R.id.rvApprove)
    RecyclerView rvApprove;
    @BindView(R.id.ivImage)
    ImageView ivImage;
    @BindView(R.id.rlApproveEmpty)
    RelativeLayout rlApproveEmpty;
    @BindView(R.id.scrollContent)
    NiceNestedScrollView scrollContent;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.llProgressBar)
    LinearLayout llProgressBar;
    @BindView(R.id.tvCreateTime)
    TextView tvCreateTime;
    @BindView(R.id.tvOrderNo)
    TextView tvOrderNo;
    @BindView(R.id.tvOrderCompany)
    TextView tvOrderCompany;
    @BindView(R.id.tvOrderArea)
    TextView tvOrderArea;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.tvOrderContract)
    TextView tvOrderContract;
    @BindView(R.id.rlContract)
    RelativeLayout rlContract;

    private static final String ORDER_ID = "order_id";
    private String orderId;
    private EasyPopup mEasyPopup;
    private String mStatus;
    // 标记是否来源与合同
    private boolean isFromContract;

    public static void show(Activity activity, String orderID) {
        Intent intent = new Intent(activity, POrderDetailActivity.class);
        intent.putExtra(ORDER_ID, orderID);
        activity.startActivity(intent);
    }

    private List<OrderProductBean> mOrderProductBeans = new ArrayList<>();
    private PsDetailProductAdapter mPsDetailProductAdapter;

    private List<OrderCommentBean> mOrderCommentBeans = new ArrayList<>();
    private PsDetailCommentAdapter mPsDetailCommentAdapter;
    private TipDialog mDropDialog;

    @Override
    protected void init() {
        if (null != getIntent()) {
            orderId = getIntent().getStringExtra(ORDER_ID);
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_porder_detail;
    }


    private void showLoading() {
        bottom.setVisibility(View.GONE);
        scrollContent.setVisibility(View.GONE);
        llErrorNetwork.setVisibility(View.GONE);
        llProgressBar.setVisibility(View.VISIBLE);
    }


    private void showError() {
        bottom.setVisibility(View.GONE);
        scrollContent.setVisibility(View.GONE);
        llErrorNetwork.setVisibility(View.VISIBLE);
        llProgressBar.setVisibility(View.GONE);
    }

    private void showContent() {
        bottom.setVisibility(View.VISIBLE);
        scrollContent.setVisibility(View.VISIBLE);
        llErrorNetwork.setVisibility(View.GONE);
        llProgressBar.setVisibility(View.GONE);
    }

    @Override
    protected OrderDetailAtPresenter createPresenter() {
        return new OrderDetailAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("采购订单详情");
        showLoading();
        initAdapter();
    }

    private void initPopMenu() {
        mEasyPopup = EasyPopup.create()
                .setContext(this)
                .setContentView(R.layout.pop_menu_more_detail)
                .setAnimationStyle(R.style.RightTop2PopAnim)
                .setOnViewListener(new EasyPopup.OnViewListener() {
                    @Override
                    public void initViews(View view, EasyPopup basePopup) {
                        TextView tvEdit =  view.findViewById(R.id.tvEdit);
                        TextView tvApprove = view.findViewById(R.id.tvApprove);
                        TextView tvDelete = view.findViewById(R.id.tvDelete);
                        if (!OrderStatus.ALREADY_REJECTED.getStatus().equals(mStatus)){
                            tvApprove.setVisibility(View.VISIBLE);
                        }else {
                            tvApprove.setVisibility(View.GONE);
                        }

                        tvEdit.setOnClickListener(v -> {
                            mEasyPopup.dismiss();
                            handEditListener();
                        });

                        tvApprove.setOnClickListener(v -> {
                            mEasyPopup.dismiss();
                            handleApprovalListener();
                        });

                        tvDelete.setOnClickListener(v -> {
                            mEasyPopup.dismiss();
                            handleDelListener();
                        });
                    }
                })
                .setFocusAndOutsideEnable(true)
                .apply();
    }


    // 点击事件的监听...
    private void handEditListener(){
        if (isFromContract){
            PCntOrderEditActivity.show(this,orderId);
        }else {
            PNormalOrderEditActivity.show(this,orderId);
        }
    }

    private void handleApprovalListener(){
        POrderEnsureActivity.show(this,orderId);
    }

    private void handleDelListener(){
        showDropDialog();
    }

    private void initAdapter() {
        // 设置商品的Adapter
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvOrderDetail.setHasFixedSize(true);
        rvOrderDetail.setNestedScrollingEnabled(false);
        rvOrderDetail.setLayoutManager(manager);
        rvOrderDetail.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this,0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mPsDetailProductAdapter = new PsDetailProductAdapter(R.layout.item_order_product_detail,mOrderProductBeans);
        rvOrderDetail.setAdapter(mPsDetailProductAdapter);

        // 设置评论的Adapter
        LinearLayoutManager managerComment = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        managerComment.setSmoothScrollbarEnabled(true);
        managerComment.setAutoMeasureEnabled(true);
        rvApprove.setHasFixedSize(true);
        rvApprove.setNestedScrollingEnabled(false);
        rvApprove.setLayoutManager(managerComment);
        rvApprove.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this,0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mPsDetailCommentAdapter = new PsDetailCommentAdapter(R.layout.item_order_comment_detail,mOrderCommentBeans);
        rvApprove.setAdapter(mPsDetailCommentAdapter);
    }

    @Override
    protected void initData() {
        mPresenter.queyOrderDetail(orderId);
    }

    @Override
    protected void initListener() {
        // 设置数据监听....
        ivToolbarNavigation.setOnClickListener(v -> finish());

        btnNextRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading();
                mPresenter.queyOrderDetail(orderId);
            }
        });

        ibToolbarMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu(v);
            }
        });
    }

    private void showDropDialog(){
        if (mDropDialog == null){
            mDropDialog = new TipDialog.Builder(this)
                    .setMessage("确定作废订单？")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            mPresenter.dropOrderByID(orderId);
                        }
                    })
                    .build();
        }
        mDropDialog.show();
    }

    private void showMenu(View view) {
        int offsetX = DisplayHelper.dp2Px(20) - view.getWidth() / 2;
        int offsetY = (DisplayHelper.dp2Px(45) - view.getHeight()) / 2;
        mEasyPopup.showAtAnchorView(view, YGravity.BELOW, XGravity.ALIGN_RIGHT, offsetX, offsetY);
    }

    @Override
    public void getOrderDetailSuccess(OrderDetailBean orderDetailBean) {
        showContent();
        // 设置数据...
        // 设置人-部门
        tvUserDept.setText(ResHelper.getString(R.string.order_detail_name_dept,orderDetailBean.getBuyerName(),orderDetailBean.getDepartmentName()));
        // tag名
        tvTextSingleName.setText(orderDetailBean.getBuyerName().substring(0,1));
        // 创建时间
        tvCreateTime.setText(ResHelper.getString(R.string.order_detail_create_time, TimeUtil.getDayTime(orderDetailBean.getOrderDate())));
        // 单据编号
        tvOrderNo.setText(orderDetailBean.getOrderNo());
        // 供货单位
        tvOrderCompany.setText(orderDetailBean.getSupplierName());
        // 仓库
        tvOrderArea.setText(orderDetailBean.getAddress());

        tvTag.setText(orderDetailBean.getStatusName());
        if (OrderStatus.ALREADY_PASS.getStatus().equals(orderDetailBean.getStatus())){
            tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_pass));
        }else if (OrderStatus.ALREADY_REJECTED.getStatus().equals(orderDetailBean.getStatus())){
            tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_reject));
        }else if (OrderStatus.WAIT_SUBMIT.getStatus().equals(orderDetailBean.getStatus())){
            tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_submit));
        }else {
            tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_default));
        }

        String totalMoney = BigDecimalUtils.keep2Decimal(orderDetailBean.getTotalMoney());
        int len = totalMoney.length();
        SpannableString spannableString = new SpannableString(
                ResHelper.getString(R.string.down_order_sum,String.valueOf(orderDetailBean.getItemNum()),totalMoney));
        int totalLength = spannableString.length();
        spannableString.setSpan(new SpannableMoney(POrderDetailActivity.this),
                totalLength-len-1,totalLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvProductSum.setText(spannableString);

        // 设置订单编号
        if (TextUtils.isEmpty(orderDetailBean.getContractId())){
            this.isFromContract = false;
            rlContract.setVisibility(View.GONE);
        }else {
            this.isFromContract = true;
            rlContract.setVisibility(View.VISIBLE);
            if (null != orderDetailBean.getContractNo()){
                tvOrderContract.setText(orderDetailBean.getContractNo().toString());
            }
        }

        if (orderDetailBean.getProducts() != null){
            mOrderProductBeans.clear();
            mOrderProductBeans.addAll(orderDetailBean.getProducts());
            mPsDetailProductAdapter.notifyDataSetChanged();
        }


        // 如果是待审批 那么是无评论表的
        if (OrderStatus.WAIT_APPROVAL.getStatus().equals(orderDetailBean.getStatus()) ||
        OrderStatus.WAIT_SUBMIT.getStatus().equals(orderDetailBean.getStatus())){
            llApproveTitle.setVisibility(View.GONE);
            rvApprove.setVisibility(View.GONE);
            rlApproveEmpty.setVisibility(View.GONE);
        }else {
            llApproveTitle.setVisibility(View.VISIBLE);
            rvApprove.setVisibility(View.VISIBLE);
            // 如果为空或者是0 那么就显示空白页咯
            if (orderDetailBean.getExamines() == null || orderDetailBean.getExamines().size() == 0){
                rlApproveEmpty.setVisibility(View.VISIBLE);
            }else {
                rlApproveEmpty.setVisibility(View.GONE);
                mOrderCommentBeans.addAll(orderDetailBean.getExamines());
                mPsDetailCommentAdapter.notifyDataSetChanged();
            }
        }

        mStatus = orderDetailBean.getStatus();
        if (orderDetailBean.isFlag()){
            if (mStatus.equals(OrderStatus.WAIT_SUBMIT.getStatus())
                    || mStatus.equals(OrderStatus.ALREADY_REJECTED.getStatus())){
                ibToolbarMore.setVisibility(View.VISIBLE);
            }
        }
        initPopMenu();
        // 设置按钮是否可见....
    }

    @Override
    public void getOrderDetailFailure(String err) {
        if (!TextUtils.isEmpty(err)){
            UIUtils.showToast(err);
        }
        showError();
    }

    @Override
    public void dropOrderFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void dropOrderSuccess() {
        reBackToListAndRefresh();
    }

    /**
     * 返回列表,并通知刷新
     */
    private void reBackToListAndRefresh(){
        mRxManager.post(POrderListActivity.REFRESH_LIST,true);
        reBackToList();
    }

    /**
     * 返回列表
     */
    private void reBackToList(){
        AppManager.getAppManager().returnToActivity(POrderListActivity.class);
    }

}
